/**
 * Copyright 2020 OPSLI 快速开发平台 https://www.opsli.com
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
package org.opsli.modulars.shop.userorder.web;

import cn.hutool.core.convert.Convert;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.opsli.api.base.result.ResultWrapper;
import org.opsli.api.web.shop.shopconfig.ShopConfigRestApi;
import org.opsli.api.web.shop.userorder.ShopUserOrderRestApi;
import org.opsli.api.web.system.tenant.TenantApi;
import org.opsli.api.web.system.user.UserApi;
import org.opsli.api.wrapper.shop.userorder.ShopUserOrderModel;
import org.opsli.common.annotation.ApiRestController;
import org.opsli.common.utils.WrapperUtil;
import org.opsli.core.base.controller.BaseRestController;
import org.opsli.core.log.annotation.OperateLogger;
import org.opsli.core.log.enums.ModuleEnum;
import org.opsli.core.log.enums.OperationTypeEnum;
import org.opsli.core.persistence.Page;
import org.opsli.core.persistence.querybuilder.QueryBuilder;
import org.opsli.core.persistence.querybuilder.WebQueryBuilder;
import org.opsli.core.utils.UserUtil;
import org.opsli.modulars.shop.userorder.entity.ShopUserOrder;
import org.opsli.modulars.shop.userorder.mapper.ShopUserOrderMapper;
import org.opsli.modulars.shop.userorder.service.IShopUserOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * 用户订单 Controller
 *
 * @author 17607080935
 * @date 2024-10-31 21:09:23
 */
@Api(tags = ShopUserOrderRestApi.TITLE)
@Slf4j
@ApiRestController("/{ver}/shop/userorder")
public class ShopUserOrderRestController extends BaseRestController<ShopUserOrder, ShopUserOrderModel, IShopUserOrderService>
        implements ShopUserOrderRestApi {

    @Autowired
    ShopUserOrderMapper shopUserOrderMapper;
    @Autowired
    ShopConfigRestApi shopConfigRestApi;
    @Autowired
    TenantApi tenantApi;

    @Autowired
    UserApi userApi;
    @Autowired
    IShopUserOrderService iShopUserOrderService;

    @Override
    public void parseOrderNotifyResult(String id) {
        ShopUserOrderModel model = getById(id).getData();

        if (model == null || model.getDingjinStatus() != 0) {
            log.info("重複回調");
            return;
        }
        Integer modelStatus = model.getStatus();
        model.setDingjinStatus(1);
        model.setStatus(1);
        model.setIzManual(true);
        model.setCreateBy(model.getUid());
        model.setUpdateBy(model.getUid());
        UpdateWrapper u = new UpdateWrapper();
        u.eq("id", model.getId());
        u.set("dingjin_status", model.getDingjinStatus());
        u.set("status", 1);
        shopUserOrderMapper.update(null, u);

        if (modelStatus == 0) {
            userApi.updateVipNumber(model.getUid(), -1);
        }


    }

    /**
     * 用户订单 查一条
     *
     * @param model 模型
     * @return ResultWrapper
     */
    @ApiOperation(value = "获得单条用户订单", notes = "获得单条用户订单 - ID")
//    @PreAuthorize("hasAuthority('shop_userorder_select')")
    @Override
    public ResultWrapper<ShopUserOrderModel> get(ShopUserOrderModel model) {
        // 如果系统内部调用 则直接查数据库
        if (model != null && model.getIzApi() != null && model.getIzApi()) {
            model = IService.get(model);
        }
        return ResultWrapper.getSuccessResultWrapper(model);
    }

    @Override
    public ResultWrapper<ShopUserOrderModel> getById(String id) {
        return ResultWrapper.getSuccessResultWrapper(IService.get(id));
    }

    @Override
    public List<ShopUserOrderModel> list(QueryWrapper q) {

        return WrapperUtil.transformInstance(IService.list(q), ShopUserOrderModel.class);

    }

    /**
     * 用户订单 查询分页
     *
     * @param pageNo   当前页
     * @param pageSize 每页条数
     * @param request  request
     * @return ResultWrapper
     */
    @ApiOperation(value = "获得分页数据", notes = "获得分页数据 - 查询构造器")
//    @PreAuthorize("hasAuthority('shop_userorder_select')")
    @Override
    public ResultWrapper<?> findPage(Integer pageNo, Integer pageSize, HttpServletRequest request) {
        QueryBuilder<ShopUserOrder> queryBuilder = new WebQueryBuilder<>(IService.getEntityClass(), request.getParameterMap());
        Page<ShopUserOrder, ShopUserOrderModel> page = new Page<>(pageNo, pageSize);
        QueryWrapper q;
        q = queryBuilder.build();
        if (request.getParameterMap().containsKey("status_EQ")) {
        } else {
            q.ne("status", 0);
        }
        page.setQueryWrapper(q);
        page = IService.findPage(page);

        List<ShopUserOrderModel> list = page.getList();
        for (ShopUserOrderModel o : list) {
            String string = shopConfigRestApi.getBy(o.getOrgIds(), "title");
            o.setShopTitle(string);
            o.setUserModel(UserUtil.getUser(o.getUid()));
        }
        page.setList(list);
        return ResultWrapper.getSuccessResultWrapper(page.getPageData());
    }

    /**
     * 用户订单 查询分页
     *
     * @param pageNo   当前页
     * @param pageSize 每页条数
     * @param request  request
     * @return ResultWrapper
     */
    @ApiOperation(value = "获得分页数据", notes = "获得分页数据 - 查询构造器")
//    @PreAuthorize("hasAuthority('shop_userorder_select')")
    @Override
    public ResultWrapper<?> findPageByShop(Integer pageNo, Integer pageSize, HttpServletRequest request) {

        IPage<ShopUserOrder> page = new com.baomidou.mybatisplus.extension.plugins.pagination.Page<>(pageNo, pageSize); // 创建一个分页对象，当前页1，每页10条
        QueryWrapper<ShopUserOrder> q = new QueryWrapper();

        if (request.getParameterMap().containsKey("status_EQ")) {
            q.eq("status", request.getParameterMap().get("status_EQ")[0]);
        } else {
            q.ne("status", 0);
        }
        q.eq("uid", UserUtil.getUser().getId());
        q.orderByDesc("date");
        IPage<ShopUserOrder> userPage = iShopUserOrderService.page(page, q); // 调用服务层进行分页查询


        List<ShopUserOrderModel> list = WrapperUtil.transformInstance(userPage.getRecords(), ShopUserOrderModel.class);
        for (ShopUserOrderModel o : list) {
            String string = shopConfigRestApi.getBy(o.getOrgIds(), "title");
            o.setShopTitle(string);
            o.setUserModel(UserUtil.getUser(o.getUid()));
        }
        Map<String, Object> map = new HashMap<>();
        map.put("rows", list);

        return ResultWrapper.getSuccessResultWrapper(map);
    }

    /**
     * 用户订单 新增
     *
     * @param model 模型
     * @return ResultWrapper
     */
    @ApiOperation(value = "新增用户订单数据", notes = "新增用户订单数据")
//    @PreAuthorize("hasAuthority('shop_userorder_insert')")
    @OperateLogger(description = "新增用户订单数据",
            module = ModuleEnum.MODULE_UNKNOWN, operationType = OperationTypeEnum.INSERT, db = true)
    @Override
    public ResultWrapper<ShopUserOrderModel> insert(ShopUserOrderModel model) {
        // 调用新增方法
        ;
        return ResultWrapper.getSuccessResultWrapper(IService.insert(model));
    }

    /**
     * 用户订单 修改
     *
     * @param model 模型
     * @return ResultWrapper
     */
    @ApiOperation(value = "修改用户订单数据", notes = "修改用户订单数据")
//    @PreAuthorize("hasAuthority('shop_userorder_update')")
    @OperateLogger(description = "修改用户订单数据",
            module = ModuleEnum.MODULE_UNKNOWN, operationType = OperationTypeEnum.UPDATE, db = true)
    @Override
    public ResultWrapper<?> update(ShopUserOrderModel model) {
        // 调用修改方法
        IService.update(model);
        return ResultWrapper.OK("修改用户订单成功");
    }


    /**
     * 用户订单 删除
     *
     * @param id ID
     * @return ResultVo
     */
    @ApiOperation(value = "删除用户订单数据", notes = "删除用户订单数据")
    @PreAuthorize("hasAuthority('shop_userorder_delete')")
    @OperateLogger(description = "删除用户订单数据",
            module = ModuleEnum.MODULE_UNKNOWN, operationType = OperationTypeEnum.DELETE, db = true)
    @Override
    public ResultWrapper<?> del(String id) {
        IService.delete(id);
        return ResultWrapper.OK("删除用户订单成功");
    }

    /**
     * 用户订单 批量删除
     *
     * @param ids ID 数组
     * @return ResultVo
     */
    @ApiOperation(value = "批量删除用户订单数据", notes = "批量删除用户订单数据")
    @PreAuthorize("hasAuthority('shop_userorder_delete')")
    @OperateLogger(description = "批量删除用户订单数据",
            module = ModuleEnum.MODULE_UNKNOWN, operationType = OperationTypeEnum.DELETE, db = true)
    @Override
    public ResultWrapper<?> delAll(String ids) {
        String[] idArray = Convert.toStrArray(ids);
        IService.deleteAll(idArray);
        return ResultWrapper.OK("批量删除用户订单成功");
    }

    /**
     * 用户订单 Excel 导出认证
     *
     * @param type    类型
     * @param request request
     */
    @ApiOperation(value = "Excel 导出认证", notes = "Excel 导出认证")
    @PreAuthorize("hasAnyAuthority('shop_userorder_export', 'shop_userorder_import')")
    @Override
    public ResultWrapper<String> exportExcelAuth(String type, HttpServletRequest request) {
        Optional<String> certificateOptional =
                super.excelExportAuth(type, ShopUserOrderRestApi.SUB_TITLE, request);
        if (!certificateOptional.isPresent()) {
            return ResultWrapper.getErrorResultWrapper();
        }
        return ResultWrapper.getSuccessResultWrapper(certificateOptional.get());
    }


    /**
     * 用户订单 Excel 导出
     *
     * @param response response
     */
    @ApiOperation(value = "导出Excel", notes = "导出Excel")
    @PreAuthorize("hasAuthority('shop_userorder_export')")
    @OperateLogger(description = "用户订单 导出Excel",
            module = ModuleEnum.MODULE_UNKNOWN, operationType = OperationTypeEnum.SELECT, db = true)
    @Override
    public void exportExcel(String certificate, HttpServletResponse response) {
        // 导出Excel
        super.excelExport(certificate, response);
    }

    /**
     * 用户订单 Excel 导入
     * 注：这里 RequiresPermissions 引入的是 Shiro原生鉴权注解
     *
     * @param request 文件流 request
     * @return ResultVo
     */
    @ApiOperation(value = "导入Excel", notes = "导入Excel")
    @PreAuthorize("hasAuthority('shop_userorder_import')")
    @OperateLogger(description = "用户订单 Excel 导入",
            module = ModuleEnum.MODULE_UNKNOWN, operationType = OperationTypeEnum.INSERT, db = true)
    @Override
    public ResultWrapper<?> importExcel(MultipartHttpServletRequest request) {
        return super.importExcel(request);
    }

}